package com.zhuang.taiqiu.config;

import com.zhuang.taiqiu.model.Player;
import com.zhuang.taiqiu.model.RoomInfo;
import com.zhuang.taiqiu.model.User;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 这个里面添加退出的功能
 */
@Slf4j
public class SessionManage {
	/**
	 * userID 映射 连接channel
	 */

	private static Map<Long, Player> userOpenidChannelMap = new ConcurrentHashMap<>(128);
	
	/**
	 * groupId ---> channelgroup 群聊ID和群聊ChannelGroup映射
	 */
	private static Map<Long, RoomInfo> groupIdChannelGroupMap = new ConcurrentHashMap<>();

	/**当前进入匹配的账号**/
	private static Queue<Long> matchQueue = new LinkedList<>();


	public static void bindChannel(User user, Channel channel) {
		channel.attr(AttributeKey.valueOf("userId")).set(user.getId());/**把userId放进channel**/
		userOpenidChannelMap.put(user.getId(), new Player(user, channel));
		log.info("openid为【"+user.getId() + "】的用户已经登陆...");
		log.info("当前channelMap为"+userOpenidChannelMap.toString());
	}
	public static void clearChannel(Long userId) {
		userOpenidChannelMap.remove(userId);
		matchQueue.remove(userId);

		groupIdChannelGroupMap.forEach((groupId, roomInfo) -> {
			// 在这里处理roomInfo
			if(roomInfo.getPlayerA().getUser().getId().equals(userId) || roomInfo.getPlayerB().getUser().getId().equals(userId)){
				groupIdChannelGroupMap.remove(groupId);
				/**这里其实还要优化，如果房间内只退出了一个人，另一个可以继续在内
				 * 或者那个人是断线了，但可以在限定时间回来到这个房间
				 * 如果是逃跑的，就直接删除房间吧*/
			}
		});
		log.info("用户【" + userId + "】已经退出...剩余在线人数：" + userOpenidChannelMap.size());
	}

	/**
	 * 通过openid来进行channel的发送
	 * @param openid
	 * @return
	 */
	public static Player getChannel(Long openid) {
		return userOpenidChannelMap.get(openid);
	}
	/**
	 * 绑定群聊Id  群聊channelGroup
	 * @param groupId
	 * @param roomInfo
	 */
	public static void bindChannelGroup(Long groupId, RoomInfo roomInfo) {
		groupIdChannelGroupMap.put(groupId, roomInfo);
		log.info("当前channelGroup" + roomInfo.getChannelGroup().toString());
	}


	public static Long getMatch(Long userId){
		for (Long playerId : matchQueue) {
			if (!playerId.equals(userId)) {
				return playerId;
			}
		}
		return null;
	}

	public static void putMatch(Long userId){
		if(!matchQueue.contains(userId)){
			matchQueue.add(userId);
		}
	}

	public static void delMatch(Long userId){
		if(null != userId){
			matchQueue.remove(userId);
		}
	}

	/**
	 * 获取房间对象
	 * @param groupId
	 * @return
	 */
	public static RoomInfo getChannelRoomInfo(Long groupId) {
		return groupIdChannelGroupMap.get(groupId);
	}

	public static Map<Long, Player>  getAllOnlineChannel() {
		return userOpenidChannelMap;
	}
}
